#
# Copyright 2009 Jeffrey Palm
#
require 'cgi'
require 'util'
require 'config'
require 'server'
require 'key_finder'
require 'has_a_shared_key'

# Retrieves the shared key from our server using the unique id
class RetrievesKeyFromSever < KeyFinder

  attr_reader :config
  attr_reader :has_unique_id

  def initialize(config,has_a_unique_id)
    @config          = config
    @has_a_unique_id = has_a_unique_id
  end

  def find_the_shared_key
    shared_key = get_the_shared_key
    #send_shared_key shared_key
    shared_key
  end 

  # Gets a new shared key from the server -- public for testing
  def get_the_shared_key
    url = url(@config,'get_id.php') + '?user=' + CGI.escape(@has_a_unique_id.unique_id)
    last_line open_and_read(url)
  end

  private

  def send_shared_key(shared_key)
    note 'Sending shared key' + shared_key
    s = TCPSocket.open @config.addr,@config.port
    s.puts shared_key
    s.close
  end

end
